import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App.jsx'
import './index.css'
import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/dist/helper'

/**
 * React子应用入口文件
 * @description 初始化React应用并集成qiankun生命周期
 */

// 渲染应用
let root = null
const render = (props = {}) => {
  const { container } = props
  const targetContainer = container ? container.querySelector('#root') : document.getElementById('root')
  
  // 创建新的root实例
  root = ReactDOM.createRoot(targetContainer)
  
  root.render(
    <React.StrictMode>
      <BrowserRouter basename={window.__POWERED_BY_QIANKUN__ ? '/react-app' : '/'}>
        <App {...props} />
      </BrowserRouter>
    </React.StrictMode>
  )
}

// 独立运行时直接渲染
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  render()
}

// 集成qiankun生命周期
renderWithQiankun({
  mount(props) {
    render(props)
  },
  bootstrap() {},
  unmount() {
    if (root) {
      root.unmount()
      root = null
    }
  },
  update() {}
}) 